public class Thread_Producer_Customer {

    public static void main(String[] args) {
        Buffer buffer = new Buffer();
        Customer customer = new Customer(buffer);
        Producer producer = new Producer(buffer);
        customer.start();
        producer.start();
    }

}

//产品
class Goods{
    int id;

    public Goods(int id) {
        this.id = id;
    }
}

//缓冲区
class Buffer{
    Goods[] goods = new Goods[5];
    int count = 0;
    int i = 0;
    //往缓冲区放产品
    public synchronized void push(Goods goods) {
        if (count >= this.goods.length){ //缓冲区满
            try {
                this.wait(); //阻塞自己
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.goods[count++] = goods; //放入缓冲区
        System.out.println("生产第"+ i++ +"个产品");
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        this.notifyAll(); //通知消费者消费
    }

    //消费
    public synchronized Goods pop(){
        if (count <= 0){ //缓冲区空
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        Goods good = this.goods[--count];
        System.out.println("消费了第-----》"+ good.id +"个产品");
        this.notifyAll(); //通知生产者生产
        return good;
    }
}

//生产者
class Producer extends Thread{
    Buffer buffer;

    public Producer(Buffer buffer) {
        this.buffer = buffer;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            buffer.push(new Goods(i));
        }
    }
}

//消费者
class Customer extends Thread{
    Buffer buffer;

    public Customer(Buffer buffer) {
        this.buffer = buffer;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            Goods goods = buffer.pop();
        }
    }
}